package com.jt.chapter06.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.chapter06.common.BodyReaderHttpServletRequestWrapper;
import com.jt.chapter06.utils.ImageCode;
import com.jt.chapter06.common.SessionKey;
import com.jt.chapter06.common.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author jiang tao
 * @date 2022/1/19
 * @description:
 **/
@Slf4j
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Autowired
    private CustomizeAuthenticationFailureHandler customizeAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (request.getRequestURI().contains("login")
                && request.getMethod().equalsIgnoreCase("post")) {
            BodyReaderHttpServletRequestWrapper bodyReaderHttpServletRequestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            // 开始验证
            try {
                validateCode(new ServletWebRequest(bodyReaderHttpServletRequestWrapper));
            } catch (ValidateCodeException e) {
                // 如果验证失败，就使用自定义验证处理器
                customizeAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
            filterChain.doFilter(bodyReaderHttpServletRequestWrapper, response);

        }else {
            filterChain.doFilter(request, response);
        }
    }

    private void validateCode(ServletWebRequest servletWebRequest) throws IOException {
        Map<String, String> loginData = new HashMap<>();
        HttpServletRequest request = servletWebRequest.getRequest();
        loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
        String imageCode = loginData.get("imageVerficationCode");
        ImageCode sessionCode = (ImageCode) request.getSession().getAttribute(SessionKey.SESSION_key);
        if(StringUtils.isEmpty(imageCode)) {
            throw new ValidateCodeException("验证码不能为空 ");
        }
        if (sessionCode == null) {
            throw new ValidateCodeException("验证码在服务器上不存在 ");
        }
        if (!sessionCode.getCode().equals(imageCode)) {
            throw new ValidateCodeException("前端的验证码与服务器验证码不一致");
        }


    }
}
